package struct;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import struct.enums.State;
import struct.enums.ValueType;

import java.util.List;

public class SensorInfo {
    public static final String SENSOR_NAME_FIELD = "sensor_name";
    public static final String VALUE_TYPE_FIELD = "value_type";
    public static final String FIELDS_FIELD = "fields";
    public static final String SENSOR_STATE_FIELD = "state";
    public static final String SENSOR_APPS_FIELD = "apps";

    public String name;
    public ValueType type;
    public List<String> fields;
    public State state;
    public List<String> apps;
    private JSONObject jo;

    public SensorInfo(String name, ValueType type, List<String> fields, State state, List<String> apps) {
        this.state = state;
        this.type = type;
        this.name = name;
        this.fields = fields;
        this.apps = apps;
    }

    public SensorInfo(JSONObject obj) {
        this.jo = obj;
        this.state = State.fromString(obj.getString(SENSOR_STATE_FIELD));
        this.type = ValueType.fromString(obj.getString(VALUE_TYPE_FIELD));
        this.name = obj.getString(SENSOR_NAME_FIELD);
        JSONArray ja = obj.getJSONArray(FIELDS_FIELD);
        fields = ja.toJavaList(String.class);
        ja = obj.getJSONArray(SENSOR_APPS_FIELD);
        apps = ja.toJavaList(String.class);
    }

    @Override
    public String toString() {
        if (jo != null) return jo.toJSONString();
        return this.toJSONObject().toJSONString();
    }

    public JSONObject toJSONObject() {
        if (jo != null) return jo;
        jo = new JSONObject();
        jo.put(SENSOR_NAME_FIELD, name);
        jo.put(VALUE_TYPE_FIELD, type.toString());
        JSONArray ja = new JSONArray();
        ja.addAll(fields);
        jo.put(FIELDS_FIELD, ja);
        jo.put(SENSOR_STATE_FIELD, state.toString());
        ja = new JSONArray();
        ja.addAll(apps);
        jo.put(SENSOR_APPS_FIELD, ja);

        return jo;
    }

    public String getStatus() {
        return state.toString();
    }
}
